package com.acme.test;

import java.util.Iterator;

import org.hamcrest.core.Is;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Assert;

import com.acme.StartServer;
import com.acme.domain.Operationtype;
import com.acme.domain.Order;
import com.acme.domain.Orderstatus;
import com.acme.domain.Responses;
import com.acme.domain.StartClient;
import com.acme.domain.Writer;
import com.acme.domain.request.PlaceOrderRequest;
import com.acme.domain.response.OrderChangeInfo;
import com.acme.domain.response.PlaceOrderResponse;

public class PlaceTestCase {
	
	@BeforeClass
	public static void setUpBeforeClass(){
		StartServer.start(2013);
	}
	
	@Before 
	public void setUp() throws Exception {
		StartClient.start("127.0.0.1", 2013, "Oleg");
	}

	@Test
	public void shouldRecieveAcknowledgementWhenPlaceCorrectOrder() throws InterruptedException {
		Order order = new Order("Oleg", Operationtype.BUY, "TNK", 10, 10, 1);

		Writer.writeRequest(new PlaceOrderRequest(order));

		Iterator<OrderChangeInfo> it = Responses.get().iterator();
		OrderChangeInfo resp = it.next();
		
		Assert.assertThat("Not correct response", 
				resp, Is.is(PlaceOrderResponse.class));
		Assert.assertThat("Not correct status", 
				((PlaceOrderResponse)resp).getOrder().getStatus(), Is.is(Orderstatus.ACCEPTED));
	}
	
	@Test
	public void shouldRecieveRejectWhenPlaceIncorrectOrder() throws InterruptedException{
		Order order = new Order("Oleg", Operationtype.BUY, "TNK", -10, -10, 2);
		Writer.writeRequest(new PlaceOrderRequest(order));
		Iterator<OrderChangeInfo> it = Responses.get().iterator();
		OrderChangeInfo resp = it.next();
		Assert.assertThat("Not correct response", 
				resp, Is.is(PlaceOrderResponse.class));
		Assert.assertThat("Not correct status", 
				((PlaceOrderResponse)resp).getOrder().getStatus(), Is.is(Orderstatus.REJECTED));
	}
	
	
	@After
	public void tearDown() throws Exception{
		Responses.get().clear();
		StartClient.shutdown();
	}
	
	@AfterClass
	public static void tearDownAfterClass() throws Exception{
		StartServer.shutdown();
	}
}
